import express from 'express';
import Mock from 'mockjs';
import bodyParser from 'body-parser';
import jwt from 'jsonwebtoken';

const app = express();
const port = 3000;
const SECRET_KEY = 'your_secret_key';

// 使用 body-parser 中间件解析请求体
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 设置允许跨域的响应头
app.use((req, res, next) => {
  // 设置允许所有来源访问，生产环境建议指定具体的来源
  res.setHeader('Access-Control-Allow-Origin', '*');
  // 设置允许的 HTTP 请求方法
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  // 设置允许的请求头，添加了 authorization
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, authorization');

  // 处理预检请求（OPTIONS 请求）
  if (req.method === 'OPTIONS') {
      // 预检请求直接返回 200 状态码
      res.sendStatus(200);
  } else {
      // 非预检请求继续处理
      next();
  }
});

// 创建一个用户名和密码以及角色映射表
const USER_MAP = new Map([
  ['admin', { username: 'admin', password: 'admin123', role: 'admin' }],
  ['guest', { username: 'guest', password: 'guest123', role: 'guest' }],
]);

// 创建一个权限列表，目前根据角色返回对应的路由权限、名称和图标
const ROLE_PERMISSIONS_MAP = new Map([
  ['admin', [
    {
      component: "orders",
      path: '/orders',
      name: 'orders',
      meta: { islink: true, title: '订单管理', icon: 'Document', actions: ['create', 'read', 'update', 'delete'] }
    },
    {
      component: "users",
      path: '/users',
      name: 'users',
      actions: ['create', 'read', 'update', 'delete'],
      meta: { islink: true, title: '用户管理', icon: 'User', actions: ['create', 'read', 'update', 'delete'] }
    },
    {
      component: "dashboard",
      path: '/dashboard',
      name: 'dashboard',
      actions: ['read'],
      meta: { islink: true, title: '仪表盘', icon: 'Stopwatch', actions: ['create', 'read', 'update', 'delete'] }
    },
    {
      component: "routerView",
      name: 'production',
      path: '/production',
      actions: ['read'],
      meta: { islink: false, title: '生产管理', icon: 'DishDot' },
      children: [
        {
          component: "process",
          path: 'process',
          name: 'process',
          actions: ['create', 'read', 'update', 'delete'],
          meta: { islink: true, title: '工序管理', icon: 'DishDot', actions: ['create', 'read', 'update', 'delete'] }
        },
        {
          component: "materials",
          path: 'materials',
          name: 'materials',
          actions: ['create', 'read', 'update', 'delete'],
          meta: { islink: true, title: '原料管理', icon: 'box', actions: ['create', 'read', 'update', 'delete'] }
        },
      ]
    },
    {
      path: "/patient",
      component: "routerView",
      name: "PatientManagement",
      meta: {
        title: "患者管理",
        icon: "patient"
      },
      children: [
        {
          path: "outpatient",
          component: "OutpatientPatient",
          name: "OutpatientPatientPage",
          meta: {
            title: "门诊患者",
            icon: "outpatient"
          },
          children: [
            {
              path: "registration",
              component: "PatientRegistration",
              name: "PatientRegistrationPage",
              meta: {
                title: "患者挂号",
                icon: "registration"
              }
            },
            {
              path: "medical-record",
              component: "OutpatientMedicalRecord",
              name: "OutpatientMedicalRecordPage",
              meta: {
                title: "门诊病历录入",
                icon: "medical-record"
              }
            }
          ]
        },
        {
          path: "inpatient",
          component: "InpatientPatient",
          name: "InpatientPatientPage",
          meta: {
            title: "住院患者",
            icon: "inpatient"
          },
          children: [
            {
              path: "admission",
              component: "PatientAdmission",
              name: "PatientAdmissionPage",
              meta: {
                title: "患者入院办理",
                icon: "admission"
              }
            },
            {
              path: "doctor-order",
              component: "DoctorOrderManagement",
              name: "DoctorOrderManagementPage",
              meta: {
                title: "医嘱管理",
                icon: "doctor-order"
              }
            }
          ]
        }
      ]
    }
  ]],
  ['guest', [
    {
      path: 'home',
      name: '首页',
      icon: 'home',
      actions: ['read'],
      meta: { islink: true }
    },
    {
      path: 'orders',
      name: '订单管理',
      icon: 'Document',
      actions: ['read'],
      meta: { islink: true }
    },
  ]],
]);

// 模拟用户数据
const mockUsers = Mock.mock({
  'list|20': [
    {
      'id|+1': 1,
      'name': '@cname',
      'age|18-60': 1,
      'gender|1': ['男', '女'],
      'email': '@email'
    }
  ]
});

// 生成JWT
const generateToken = (payload) => {
  return jwt.sign(payload, SECRET_KEY, { expiresIn: '1h' });
};

// 验证JWT
const verifyToken = (token) => {
  return new Promise((resolve, reject) => {
    jwt.verify(token, SECRET_KEY, (err, decoded) => {
      if (err) {
        reject(err);
      } else {
        resolve(decoded);
      }
    });
  });
};

//浏览器url请求返回一个你好文字
app.get('/Hello', (req, res) => {
  res.send('Hello, world!');
});

// 处理用户列表查询接口，支持条件查询
app.get('/api/userList', (req, res) => {
  const { name, gender } = req.query;
  let filteredUsers = mockUsers.list;

  if (name) {
    filteredUsers = filteredUsers.filter(user => user.name.includes(name));
  }

  if (gender) {
    filteredUsers = filteredUsers.filter(user => user.gender === gender);
  }

  res.json({
    code: 200,
    message: 'success',
    data: filteredUsers
  });
});

// 处理删除用户接口
app.delete('/api/user/:id', (req, res) => {
  const id = parseInt(req.params.id);
  mockUsers.list = mockUsers.list.filter(user => user.id !== id);
  res.json({
    code: 200,
    message: '删除成功'
  });
});

// 模拟登录接口
app.post('/api/login', async (req, res) => {
  const { username, password } = req.body;
  const user = USER_MAP.get(username);
  if (user && user.password === password) {
    // 生成JWT
    const token = generateToken({ username, password });
    res.json({
      code: 200,
      message: '登录成功',
      data: {
        token: token,
        user
      },
    });
  } else {
    res.status(401).json({
      code: 401,
      message: '用户名或11密码错误',
    });
  }
});

// 模拟获取权限列表接口
app.get('/api/getRolesPermissions', async (req, res) => {
  debugger;
  const token = req.headers.authorization.split(' ')[1];
  try {
    const decoded = await verifyToken(token);
    res.json({
      code: 200,
      message: 'success',
      data: {
        // 返回权限列表数据
        permissions: ROLE_PERMISSIONS_MAP.get(USER_MAP.get(decoded.username).role),
      },
    });
  } catch (err) {
    res.status(401).json({
      code: 401,
      message: '无效的token',
    });
  }
});

// 校验 token 是否有效
app.get('/api/verifyToken', async (req, res) => {
  const token = req.headers.authorization.split(' ')[1];
  try {
    const decoded = await verifyToken(token);
    res.json({
      code: 200,
      message: 'token有效',
      data: {
        user: USER_MAP.get(decoded.username),
      },
    });
  } catch (err) {
    res.status(401).json({
      code: 401,
      message: '无效的token',
    });
  }
});

// 启动服务器
app.listen(port, () => {
  console.log(`Mock server is running on port ${port}`);
});
